package com.init.bootframe.config.Filter;

import com.init.bootframe.util.TmompEncryptUtil;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.nio.charset.Charset;

/**
 * 自定义request对象 复制HttpServletRequest 内容 以便重复使用
 */
public class BodyReaderHttpServletRequestWrapper extends HttpServletRequestWrapper {

    private Logger logger = LoggerFactory.getLogger(BodyReaderHttpServletRequestWrapper.class);

    private static String body;

    public BodyReaderHttpServletRequestWrapper(HttpServletRequest request) {
        super(request);
        try {
            String sessionStream = getRequestMessage(request);
            if (!sessionStream.equals(null) && !sessionStream.equals("")) {
                logger.info("需解密参数："+sessionStream);
                sessionStream = TmompEncryptUtil.aesDecrypt(sessionStream.replaceAll("\"", ""));// 解密
                logger.info("解密后参数："+sessionStream);
                sessionStream = sqlValidate(sessionStream);// 过滤字符
                logger.info("过滤后参数："+sessionStream);
            }
            body = sessionStream;
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        ByteArrayInputStream bais = new ByteArrayInputStream(body.getBytes(Charset.forName("UTF-8")));
        return new ServletInputStream() {
            @Override
            public int read() throws IOException {
                return bais.read();
            }
            @Override
            public boolean isFinished() {
                return false;
            }
            @Override
            public boolean isReady() {
                return false;
            }
            @Override
            public void setReadListener(ReadListener readListener) {
            }
        };
    }

    /**
     * 获取 HttpServletRequest 中的参数内容
     * @param request
     */
    public String getRequestMessage(HttpServletRequest request) {
        String body = "";
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader bufferedReader = null;
        InputStream inputStream = null;
        try {
            inputStream = request.getInputStream();
            if (inputStream != null) {
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                char[] charBuffer = new char[128];
                int bytesRead = -1;
                while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
                    stringBuilder.append(charBuffer, 0, bytesRead);
                }
            } else {
                stringBuilder.append("");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        body = stringBuilder.toString();
        return body;
    }

    /**
     * 获取当前body内容
     * @return
     */
    public static String getBody() {
        return body;
    }
    /**
     * 危险字符过滤
     *
     * @param str
     * @return
     */
    private String sqlValidate(String str) {
        String s2 = str.toLowerCase();// 统一转为小写
        String reStr = "(?i)";
        String badStr = "|,$,script,document,alert,javascript";//过滤掉的sql关键字，可以手动添加
        String[] badStrs = badStr.split(",");
        for (int i = 0; i < badStrs.length; i++) {
            if (s2.indexOf(badStrs[i]) >= 0) {
                str = str.replaceAll(reStr + badStrs[i], "");
            }
        }
        return str;
    }

    /**
     * 判断字符串是否是json格式
     * @param jsons
     * @return
     */
    private boolean judgeJson(String jsons) {
        try {
            JSONObject jsonStr =  JSONObject.fromObject(jsons);
            return true;
        }catch (Exception e) {
            return false;
        }
    }
}
